<template>
  <div class="box-all">
    <div class="description">
      <el-tree
        :data="data"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
        :render-content="renderContent">
      </el-tree>
    </div>
    <div class="container" id="container">
      <el-amap vid="amap" :plugin="plugin" class="amap-demo" :amap-manager="amapManager" :center="center" :zoom="zoom" :events='events'>
      </el-amap>
      <div class="draw" id="draw" @click="drawPolygon()">绘制区域</div>
      <div class="drag" @click="remove()">拖动区域</div>
      <div class="dialog-box">
        <el-dialog
          title="信息"
          :visible.sync="centerDialogVisible"
        >
          <div class="region">
            <span style="margin-right:10px">区域名称</span>
            <input type="text" v-model="name" style="outline:none;" placeholder="请输入区域名称" clearable></el-input>
          </div>
          <div class="color">
            <span style="margin-right:10px;">颜色区域</span>
            <el-color-picker
                v-model="color"
                size="medium"
                show-alpha
                :predefine="predefineColors"
            >
            </el-color-picker>
          </div>
          <div class="opertaion">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="save()">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
    import request from '@/utils/request'
    import {
        AMapManager
    } from "vue-amap";

    const amapManager = new AMapManager();
    export default {
        name: 'Child',
        data() {
            let self = this;
            return {
                data: [{
                    label: '全部',
                    children: []
                }],
                predefineColors: [
                    '#ff4500',
                    '#ff8c00',
                    '#ffd700',
                    '#90ee90',
                    '#00ced1',
                    '#1e90ff',
                    '#c71585',
                    'rgba(255, 69, 0, 0.68)',
                    'rgb(255, 120, 0)',
                    'hsv(51, 100, 98)',
                    'hsva(120, 40, 94, 0.5)',
                    'hsl(181, 100%, 37%)',
                    'hsla(209, 100%, 56%, 0.73)',
                    '#c7158577'
                ],
                content: '',
                code: '',
                name: '',
                color: '#409EFF',
                centerDialogVisible: false,
                amapManager: amapManager,
                // 画围栏
                fenceForm: {
                    coordinate: []
                },
                rectangle: null,
                mouseTool: null,
                overlays: [],
                tantan: false,
                address: '', //获取的位置
                zoom: 10, // 地图缩放
                // 初始中心
                center: [121.84431, 29.89889],
                lng: 0, //经纬度
                lat: 0,
                loaded: false,
                // 点击显示的标记默认的定位
                markers: [{
                    position: [121.59996, 31.197646]
                }],
                //  自动定位到当前位置
                plugin: [{
                    timeout: 100000000, //超过10秒后停止定位，默认：无穷大
                    panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
                    zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：f
                    pName: 'Geolocation',
                    pName: 'AMap.ToolBar',
                    events: {
                        click(e) {
                            alert(1);
                        },
                        // init(o) {
                        //     // o 是高德地图定位插件实例
                        //     o.getCurrentPosition((status, result) => {
                        //         console.log('高德定位');
                        //         console.log(status, result);
                        //         console.log(result.formattedAddress);
                        //         if (result && result.position) {
                        //             self.address = result.formattedAddress;
                        //             self.lng = result.position.lng;
                        //             self.lat = result.position.lat;
                        //             self.center = [self.lng, self.lat];
                        //             self.loaded = true;
                        //             self.$nextTick();
                        //         }
                        //     });
                        // }
                    }
                }],
                events: {},
                // 点击地图获取当前位置并显示标记
                // events: {
                //   click(e) {
                //     let {lng,lat} = e.lnglat;
                //     self.lng = lng;
                //     self.lat = lat;

                //     self.markers = [{
                //       position: [self.lng, self.lat],
                //       icon: '',
                //       title: '',
                //       events: {
                //         click(o) {
                //           alert( self.lng+''+self.lat);

                //         }
                //       }
                //     }];
                //     // 这里通过高德 SDK 完成。
                //     var geocoder = new AMap.Geocoder({
                //       radius: 1000,
                //       extensions: "all"
                //     });
                //     geocoder.getAddress([lng, lat], function (status, result) {
                //       if (status === 'complete' && result.info === 'OK') {
                //         if (result && result.regeocode) {
                //           self.address = result.regeocode.formattedAddress;    //获取到位置
                //           self.$nextTick();
                //         }
                //       }
                //     });
                //   }
                // }
            }
        },
        created() {
          this.query();
        },
        methods: {
            remove() {
                this.fenceForm.coordinate = []
                if (this.mouseTool) {
                    this.mouseTool.close(true)
                }
                let map = amapManager.getMap();
                if(map) {
                    map.setDefaultCursor("hand");
                }
            },
            drawPolygon() {
                let _this = this
                let map = amapManager.getMap();
                if(map){
                    map.setDefaultCursor("crosshair");
                    map.plugin(['AMap.MouseTool'], function() {
                    let mouseTool = new AMap.MouseTool(map)
                    _this.mouseTool = mouseTool
                        //添加事件
                    mouseTool.polygon({
                        strokeColor: "#FF33FF",
                        strokeOpacity: 1,
                        strokeWeight: 2,
                        strokeOpacity: 0.2,
                        fillColor: '#1791fc',
                        fillOpacity: 0.4,
                        strokeStyle: "solid",
                        strokeDasharray: [30, 10],
                        })
                    AMap.event.addListener(mouseTool, 'draw', function(e) {
                        _this.fenceForm.coordinate = []
                        let path = e.obj.getPath()
                        path.forEach(e => {
                            _this.fenceForm.coordinate.push([e.getLng(), e.getLat()])
                        })
                        _this.centerDialogVisible = true;
                        _this.code = '';
                        _this.name = '';
                        mouseTool.close(false);
                    })
                 })
                }
            },
            renderContent(h, { node, data, store }) {
                if(node.level===1){
                 return (
                 <span class="custom-tree-node">
                    <span class="tree-lable" title={node.label}>{node.label}</span>
                </span>);
               }else {
                return (
                 <span class="custom-tree-node">
                    <span class="tree-lable" title={node.label}>{node.label}</span>
                    <span class="tree-btn">
                        <span class="common-btn del-btn" type="text" on-click={ () => this.update(data) }>修改</span>
                        <span class="common-btn" type="text" on-click={ () => this.funcDelete(node, data) }>删除</span>
                    </span>
                </span>);
              }
            },
            cancel() {
                this.centerDialogVisible = false;
                if (this.mouseTool) {
                    this.mouseTool.close(true)
                }
            },
            // 添加 or 修改 centerDialogVisible = false
            save() {
                let _this = this;
                // 修改
                if (_this.code != '') {
                    request({
                        url: `/ntocc-basic-api/distributionArea`,
                        method: "PUT",
                        params: {
                            areaColor: _this.color,
                            name: _this.name,
                            code: _this.code
                        }
                    }).then(response => {
                        _this.centerDialogVisible = false;
                        _this.query();
                    });
                }
                // 新增
                else {
                    let  shipmentUserCode = this.$route.query.partyCode
                    request({
                        url: `/ntocc-basic-api/distributionArea`,
                        method: "POST",
                        params: {
                            areaColor: _this.color,
                            name: _this.name,
                            shipmentUserCode,
                            longitudeAndLatitude: JSON.stringify(_this.fenceForm.coordinate)
                        }
                    }).then(response => {
                        _this.centerDialogVisible = false;
                        _this.query();
                    });
                }
            },
            // 修改按钮弹出对话框
            update(data) {
                let _this = this;
                _this.code = data.code;
                _this.name = data.name;
                _this.color = data.areaColor;
                _this.centerDialogVisible = true;
            },
            // 删除方法
            funcDelete(node, data) {
                let _this = this;
                _this.$confirm('确认删除吗？').then(_ => {
                    request({
                        url: `/ntocc-basic-api/distributionArea/delete`,
                        method: 'DELETE',
                        params: {
                            code: data.code
                        }
                    }).then(response => {
                        _this.$message({
                            message: response.msg,
                            type: 'success'
                        })
                        _this.query();
                    })
                }).catch(_ => {});
            },
            // 查询
            query() {
                let _this = this;
                let  shipmentUserCode = this.$route.query.partyCode
                request({
                    url: `/ntocc-basic-api/distributionArea`,
                    method: "GET",
                    params: {
                        pageSize: 100,
                        shipmentUserCode
                    }
                }).then(response => {
                    _this.data[0].children = response.data.records;
                    let map = amapManager.getMap();
                    if(map){
                       // 先清除地图上的所有覆盖物
                        // 循环绘制多边形区域
                        map.clearMap();
                        response.data.records.forEach((item, index) => {
                            var longitudeAndLatitude = JSON.parse(item.longitudeAndLatitude);
                            var polygon = new AMap.Polygon({
                                path: longitudeAndLatitude,
                                strokeColor: item.areaColor,
                                strokeWeight: 6,
                                strokeOpacity: 0.2,
                                fillOpacity: 0.4,
                                fillColor: item.areaColor,
                                zIndex: 50,
                            })
                            map.add(polygon);
                            // 多边形区域上显示对应的name
                            // 创建纯文本标记
                            var text = new AMap.Text({
                                text: item.name,
                                anchor: 'center', // 设置文本标记锚点
                                draggable: true,
                                cursor: 'pointer',
                                position: this.getTheAreaCenter(longitudeAndLatitude)
                            });
                            text.setMap(map);
                        })
                        // 根据覆盖物调整地图范围
                      map.setFitView();
                    }
                });
            },
            //计算多变形中心坐标
            getTheAreaCenter(lnglatarr) {
                var total = lnglatarr.length;
                var X = 0,
                    Y = 0,
                    Z = 0;
                for (var i = 0; i < total; i++) {
                    var lng = lnglatarr[i].lng;
                    var lat = lnglatarr[i].lat;
                    X += lng;
                    Y += lat;
                };
                X = X / total;
                Y = Y / total;
                var result = [];
                result[0] = X;
                result[1] = Y;
                return result;
            }
        }
    }
</script>
<style lang="scss" scoped>
    .dialog-footer {
        margin-top: 50px;
    }

    .box-all {
        height: 1000px;
        display: flex;
        .container {
            cursor: crosshair !important;
            flex: 1;
            height: 100%;
            position: relative;
            .draw {
                padding: 5px 10px;
                top: 30px;
                left: 70px;
                position: absolute;
                z-index: 999;
                border-radius: 4px;
                color: #FFFFFFFF;
                cursor: pointer;
                background-color: #2C50F6FF;
                font-size: 14px;
            }
            .drag {
                padding: 5px 10px;
                top: 30px;
                left: 160px;
                position: absolute;
                z-index: 999;
                border-radius: 4px;
                color: #FFFFFFFF;
                cursor: pointer;
                background-color: #FF7500FF;
                font-size: 14px;
            }
            .dialog-box {
                position: relative;
                .region {
                    margin-bottom: 20px;
                    input {
                        height: 30px;
                        width: 50%;
                        box-sizing: border-box;
                        font-size: 14px;
                        font-weight: 400;
                    }
                }
                .color {
                    margin-bottom: 30px;
                    display: flex;
                    align-items: center;
                }
                .opertaion {
                    position: absolute;
                    bottom: 10px;
                    right: 10px;
                }
            }
            .dialog-box /deep/ .el-dialog__title {
                float: left;
            }
            /deep/ .el-dialog{
                width:500px;
            }
        }
        .description {
            min-width: 15%;
            margin-right: 20px;
            height: 100%;
        }
        .description /deep/  .el-tree-node__content{
            height: 30px;
            .custom-tree-node {
                display: flex;
                align-self: center;
                .tree-lable {
                    display: inline-block;
                    width: 80px;
                    margin-right:5px;
                    overflow:hidden; /*超出的部分隐藏起来。*/
                    white-space:nowrap;/*不显示的地方用省略号...代替*/
                    text-overflow:ellipsis;
                }
                  .common-btn {
                    display: inline-block;
                    padding: 4px 8px;
                    border-radius: 3px;
                    font-size: 12px;
                    color: #FFFFFFFF;
                    cursor: pointer;
                    background-color: #FF7500FF;
                    margin-right:4px;
                  }
                  .del-btn {
                    background-color: #2C50F6FF;
                  }
            }
        }
    }
</style>
</style>
